package com.nipun.rmi;

import java.awt.image.BufferedImage;
import java.io.File;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import javax.imageio.ImageIO;

import com.nipun.facet.neural.FacetNetworkRunner;
import com.nipun.facet.utils.Utils;


public class LoadImagesAndTrain {
	
	public static void main(String[] args){
		if (System.getSecurityManager() == null) {
            System.setSecurityManager(new SecurityManager());
        }
        try {
            String name = "NeuralService";
            Registry registry = LocateRegistry.getRegistry("localhost");
            FacetNetworkRunner runner = (FacetNetworkRunner) registry.lookup(name);

    		int xSize = 16;
    		int ySize = 12;
    		double[][] imageData = new double[xSize][ySize];
    		String dirPathToTrainTrue = "C:\\yalefaces\\test\\yes";
    		String dirPathToTrainFalse = "C:\\yalefaces\\test\\no";
    		
    		
    		File dirTrue = new File(dirPathToTrainTrue);
    		File[] trueImageFiles = dirTrue.listFiles();
    		File dirFalse = new File(dirPathToTrainFalse);
    		File[] falseImageFiles = dirFalse.listFiles();
    		int trainNum = 1000;
    		boolean which=true;
    		File[] current;
    		boolean exp = false;
    		if(trueImageFiles != null && falseImageFiles != null){
				for(int i=0; i<trainNum; i++){
					which = Math.random()>0.5?true:false;
					current = which?trueImageFiles:falseImageFiles;
					exp = which;
					BufferedImage currentimage = Utils.scale(ImageIO.read(current[(int)Math.floor(Math.random()*current.length)]), xSize, ySize);
					for(int j=0; j<xSize; j++){
						for(int k=0; k<ySize; k++){
							imageData[j][k] = currentimage.getRGB(j, k);
						}
					}
					boolean result = runner.run(imageData);
					System.out.println("expected: "+ exp +" got:: "+result);
					runner.backPropagate(exp);
				}
			}
    		
        } catch (Exception e) {
            System.err.println("exception:");
            e.printStackTrace();
        }
    }

}
